<template>
  <div>
    <!-- 客服状态 -->
    <div 
      v-if="frameForCallCenterData" 
      class="frame-quick-phoneServiceStatus"
      :class="statusClass"
      @click="handleShowDialog"
    >

      <!-- 状态图标 -->
      <span 
        class="status-dot cursor-pointer iconfont icon-zaixiandingbu" 
        v-if="has_call_center_module"
        @click="iconHandelClick"
      >
        <i class="dot" :style="{'background-color': currentStatusInfo.color}"></i>
      </span>

      <el-popover placement="bottom" trigger="click" v-if="!isInCall">
      <span slot="reference">
        <!-- 当前状态 -->
        <span class="service-status-text cursor-pointer">{{ seatStatus || currentStatusInfo.text }}</span>
      </span>

      <div class="customer-service-info">
        <div class="customer-service-top">
          <span>{{$t('system.callCenter.telCustomerService')}}</span>
          <el-dropdown placement="bottom" trigger="hover" @command="handleCommand">
            <div class="service-status-dropdown">
              <span class="dot" :style="{'background-color': currentStatusInfo.color}"></span>
              {{ currentStatusInfo.text }}
              <i class="iconfont icon-triangle-down"></i>
            </div>

            <el-dropdown-menu slot="dropdown">
              <template v-for="(item, index) in frameForCallCenterData.statusList" >
                <el-dropdown-item :key="index" :command="item.status" v-if="item.status!=frameForCallCenterData.status">
                <span class="dot" :style="{'background-color': phoneStatusMap[item.status].color}"></span>
                {{phoneStatusMap[item.status].action}}
              </el-dropdown-item>
              </template>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
        <div class="customer-service-bottom">
          <span>{{$t('common.base.serialNumber')}} {{ frameForCallCenterData.agNo || '' }}</span>
          <div class="offline-wrap mar-t-4" v-if="frameForCallCenterData.status == 0">
            <span class="mar-r-4">{{$t('system.callCenter.offlineTransfer')}}</span>
            <el-switch v-model="openOffLine" @change="openChange" :active-value="1" :inactive-value="0">></el-switch>
            <span v-show="openOffLine" @click="dialogVisible = true" class="setting-href mar-l-12">{{$t('system.callCenter.transferNumber')}}</span>
          </div>
        </div>
        <Dialpad v-if="frameForCallCenterData.status == 1 || frameForCallCenterData.status == 3" @call="makePhoneCall" ref="Dialpad"/>
      </div>
    </el-popover>
      <span v-else class="service-status-text cursor-pointer">
        {{ seatStatus || currentStatusInfo.text }}
      </span>
    </div>
    
    <!-- 通话弹窗 -->
    <div v-if="showCallCenter && callData" ref="callCenterDialogRef" class="call-center-dialog">
      <div class="dialog-header">
        <i class="el-icon-minus" @click="zoomOut"></i>
      </div>
      <div class="dialog-main">
        <div class="dialog-main-phone">
          <span class="dialog-main-phone-forwarding-text" v-if="callData.callType === 7">{{ $t('system.callCenter.text8') }}:</span>
          {{ callData.phone }}
        </div>
        <div class="dialog-main-transferSeat" v-if="callData.callType === 7">{{ `${$t('system.callCenter.text9')}: ${callData.transferSeatCaller}` }}</div>
        <div class="dialog-main-address">{{ callData.CallerAreaName }}</div>
        <div class="dialog-main-customer" v-if="callData.customerList && callData.customerList.length">
          <div 
            class="dialog-main-customer-item" 
            v-for="item in callData.customerList"
            :key="item.id"
            @click="jumpCustomerDetails(item.id)"
          >
            {{ item.customerName }}
          </div>
        </div>
        <div class="dialog-main-tags" v-if="callData.name">
          <el-tag>{{ callData.name }}</el-tag>
        </div>
        <div class="dialog-main-name">{{ callData.linkmanName || $t('callcenter.workbenchPage.unknownLinkman') }}</div>
        <div class="dialog-main-time" :style="{ 'opacity': currentTime ? 1: 0 }">{{$t('system.callCenter.calling')}}：{{ callDuration }}</div>
        <div class="dialog-main-btn" style="justify-content: center;" v-if="isOnlyShowCallOut">
          <div class="dialog-main-btn-item">
            <div class="reject" @click="callOutCancel">
              <i class="iconfont icon-dianhua2"></i>
            </div>
            <span>{{$t('system.callCenter.hangUp')}}</span>
          </div>
        </div>
        <div class="dialog-main-btn" v-else>
          <!-- 呼入 -->
          <template v-if="callData.callType === 2 || callData.callType === 7">
            <div class="dialog-main-btn-item">
              <div class="reject" @click="refusePhone">
                <i class="iconfont icon-dianhua2"></i>
              </div>
              <span>{{$t('system.callCenter.rejectCall')}}</span>
            </div>
            <div class="dialog-main-btn-item">
              <div class="accept" @click="answerPhone(isMicroSip)">
                <i class="iconfont icon-dianhua2"></i>
              </div>
              <span>{{$t('system.callCenter.answerCall')}}</span>
            </div>
          </template>
          <!-- 呼出 -->
          <template v-if="callData.callType === 1">
            <div class="dialog-main-btn-item">
              <div class="reject" @click="callOutCancel">
                <i class="iconfont icon-dianhua2"></i>
              </div>
              <span>{{$t('system.callCenter.hangUp')}}</span>
            </div>
            <div class="dialog-main-btn-item">
              <div class="jump" @click="jumpCallCenterWorkbench">
                <i class="iconfont icon-xiangzuo-copy"></i>
              </div>
              <span>{{$t('system.callCenter.jumpToWorkbench')}}</span>
            </div>
          </template>
        </div>

        <div class="dialog-main-statistics">
          <div>
            <span @click="callPopupHandleJump(1)">{{$t('common.label.todayCallIn')}}：{{ callData.todayCallInNum || 0 }}</span>
            <span @click="callPopupHandleJump(2)">{{$t('common.label.todayCallOut')}}：{{ callData.todayCallOutNum || 0 }}</span>
          </div>
          <div v-if="!callData.customerList || callData.customerList && (callData.customerList.length < 2)">
            <span @click="callPopupHandleJump(3)">{{$t('common.label.customerEvent')}}：{{ callData.unfinishedEventCount || 0 }}</span>
            <span @click="callPopupHandleJump(4)">{{$t('common.label.customerTask')}}：{{ callData.unfinishedTaskCount || 0 }}</span>
          </div>
        </div>
        <div class="dialog-main-checkbox">
          <el-checkbox v-model="isJumpCallCenterWorkbench">{{$t('system.callCenter.jumpToWorkbenchAfterAnswer')}}</el-checkbox>
        </div>
      </div>
    </div>

    <!-- start 休息状态设置转接手机号 -->
    <el-dialog
      :title="$t('system.callCenter.offlineTransfer')"
      :visible.sync="dialogVisible"
      width="500px"
      top="20vh"
      :modal-append-to-body="false"
      :close-on-click-modal="false"
      >
      <div>
        <div class="desc">{{$t('system.callCenter.offlineTransferNumber')}}</div>
        <el-input ref="dialogInput" :placeholder="$t('common.base.tip.defaultPlaceholder')" v-model="callTransferPhone" />
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">{{ $t('common.button.cancel') }}</el-button>
        <el-button type="primary" @click="updateTransferPhone">{{ $t('common.button.makeSure') }}</el-button>
      </span>
    </el-dialog>
    <!-- end 休息状态设置转接手机号 -->
  </div>
</template>

<script>
/**
 * @see http://dev1.icsoc.net/docs/develop/cti-js-sdk/cti-js-sdk-start （中通天鸿sdk文档）
 */

/* service */
import CallCenterService from '@service/CallCenterService';

import { CTIPlus } from 'cti-js-sdk' // 中通天鸿呼叫中心
import { ctiCallOut, ctiCallOutCancel, ctiSipAnswer, ctiRefuse, ctiHangup } from '@src/util/ctisdk';
import http from '@src/util/http';
import { getMenuItemId } from '@src/util/menuIdUtil';
import * as CallCenterApi from '@src/api/CallCenterApi';

import { openAccurateTab } from '@src/util/platform'
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
/** components */
import Dialpad from '@src/modules/system/frame/component/Dialpad.vue'
let CTI = null
import { getOssUrl } from '@src/util/assets'
import { useTenantId } from '@hooks/useRootWindow.ts';
const phoneImage = getOssUrl('/phone.png')
export default {
  name: 'call-center',
  components:{
    Dialpad
  },
  data() {
    return {
      phoneImage,
      phoneStatusMap: {
        1: {
          color: '#00C853',
          text: this.$t('common.base.usualStatus.working'),
          action: this.$t('frame.backgroundTask.text18'),
        },
        0: {
          color: '#D4D4D4',
          text: this.$t('common.base.usualStatus.resting'),
          action: this.$t('frame.backgroundTask.text17'),
        },
        3: {
          color: '#FAAD14',
          text: this.$t('common.base.usualStatus.busy'),
          action: this.$t('frame.backgroundTask.text22'),
        },
      },
      ctiCallOut,
      ctiCallOutCancel,
      ctiSipAnswer,
      ctiRefuse,
      showCallCenter: false,
      callData: {},
      has_call_center_module: false,
      frameForCallCenterData:null,
      callTransferPhone:'', // 转接号码
      callTransferPhoneVisible:false,
      isTalking: false,
      dialogVisible: false, // 休息状态设置转接手机号弹窗
      isMicroSip: false, //是否使用软电话
      seatStatus:'', //中通坐席状态和电话状态
      isJumpCallCenterWorkbench: true,
      callDuration: '',
      currentTime: 0,
      timer: null,
      phoneEventName: 'phoneHangup', // 电话状态事件名(默认处于通话完成状态)
      openOffLine:0 ,// 是否开启离线转接
    };
  },
  computed: {
    // 当前电话客服信息
    currentStatusInfo(){
      return this.phoneStatusMap[this.frameForCallCenterData.status];
    },
    getMenuId(){
      const id = getMenuItemId('/setting/callcenter/workbench');
      return id || '';
    },
    isOnlyShowCallOut() {
      return (this.callData?.callType === 2 || this.callData?.callType === 7) && this.isTalking === true;
    },
    // 通话中
    isInCall() {
      return this.phoneEventName != 'phoneHangup';
    },
    statusClass() {
      if(!this.isInCall) return ''

      if(this.phoneEventName == 'phoneConnect') return 'in-call' // 电话通话中
      return 'other-call' // 电话其它状态
    }
  },
  created(){
    window.initCtiSdk = this.initCtiSdk;
    window.controlCallCenter = this.controlCallCenter;

  },
  beforeDestroy() {
    this.$eventBus.$off('serviceCallCenterAutomaticWork')

    if (window.CTI) {
      // 临时用tenantId判断
      let tenantId = useTenantId().value;
      if (!['b4a3b3ba-d9fe-11e9-9cb1-506b4b2bb4ae'].includes(tenantId)) {
        // 页面关闭坐席迁出
        window.CTI.Agent.logout()
      };

      window.CTI = null
      CTI = null
    }
  },
  mounted(){
    CallCenterService.setIsCallCenterZhongTong(true);
    this.$eventBus.$on('bindingCallBack', this.bindingCallBack);
    this.$eventBus.$on('serviceCallCenterAutomaticWork', this.handleBindingAutoWork);
  
    this.getAccountInfo()
  },
  methods: {
    handleBindingAutoWork({ workIng = false }) {
      workIng ? this.handleCommand(1): this.handleCommand(0)
    },
    jumpCallCenterWorkbench() {
      this.zoomOut();
      this.openCallCenterWorkbench();
    },
    jumpCustomerDetails(id) {
      openAccurateTab({
        type: PageRoutesTypeEnum.PageCustomerView,
        key: id,
        params: 'noHistory=1',
      })
    },
    getStylesRules() {
      const endEl = document.querySelector('.frame-quick-phoneServiceStatus');
      const startEl = document.querySelector('.call-center-dialog');
      const top = endEl.offsetTop - startEl.offsetTop;
      const left = endEl.offsetLeft - startEl.offsetLeft;

      return `
        @keyframes zoomOut {
          0% {
              transform: translate(-50%, -50%) scale(1);
          }
          100% {
            transform: translate(${left}px, ${top}px) scale(0);
          }
        }`
    },
    zoomOut() {
      const rules = this.getStylesRules();
      const sheet = document.styleSheets[0]
      sheet.insertRule(rules, 0);
      this.$refs.callCenterDialogRef.style.animation = "zoomOut 0.2s linear 1";

      setTimeout(() => {
        this.showCallCenter = false;
        this.$refs.callCenterDialogRef.style.animation = "none";
        sheet.deleteRule(0);
      }, 100);
    },
    handleShowDialog() {
      if (!this.isInCall) return;

      this.showCallCenter = true;
    },
    timeFunction() {
      this.currentTime++;
      let seconds = Math.floor(this.currentTime % 60);
      let minutes = Math.floor(this.currentTime / 60) % 60;
      seconds = seconds < 10 ? `0${seconds}` : seconds;
      minutes = minutes < 10 ? `0${minutes}` : minutes;
      this.callDuration = `${minutes}:${seconds}`
    },
    handleRunTimer() {
      this.timer = setInterval(() => {
        this.timeFunction();
      }, 1000)
    },
    handleClearTimer() {
      this.currentTime = 0;
      clearInterval(this.timer);
    },
    handleCommand(command) {
      let data = this.frameForCallCenterData.statusList.find((item)=>item.status == command)
      this.changeCallCenterState(data)
      this.$track.clickStat(this.$track.formatParams('CUSTOMER_SERVICE_STATUS_SWITCHING'));
    },
    iconHandelClick(){
      this.goCallCenterWorkbench()
    },
    // 初始化呼叫中心SDK
    async initCtiSdk () {
      try{
        await this.getAgentGetToken()
        if(!this.frameForCallCenterData) return
        const { token, agentPhone, agNo,id } = this.frameForCallCenterData
        await this.queryAgentUserType(id)
        console.log(`是否软电话接听-${this.isMicroSip}`)
        // 状态为休息中强制签出
        if(this.frameForCallCenterData.status == 0){
        // 休息中不初始化
          return
        }
        // 初始化SDK
        CTI = new CTIPlus({
          token,
          agentPhone, // sip电话
          agNo, // 坐席工号
          initWithLogin: false,
          autoForceLogin: true,
          webrtc:!this.isMicroSip,
          busy:this.frameForCallCenterData.status == 3,
          renderHtml: {
            domId: 'cti-wincall',
            autoCall: false
          },
          tokenCallBack() {
          // token超时提前30min（tokenCallBackTime 默认）回调
            console.warn('呼叫中心SDK token 即将失效');
          // this.updateCtiSdkToken()
          }
        })
        window.CTI = CTI
        window.CTI.updateCtiSdkToken = this.updateCtiSdkToken
        // 初始化回调
        CTI.init(res => {
          if(res.code !== 0) return
          // 事件监听-all
          CTI.Event.add('all', async data => {
            data = this.addSourceData(data)
            const {result, code} = await CallCenterApi.agentReceiveMsg(data)
            const recordId = code === 0 && result ? result.recordId || '' : ''
            console.log('CTI WS DATA :', data)
            this.setSeatStatus(data)
            // 电话状态
            if(data.MT == 3) {
            // 设置电话状态事件名
            this.phoneEventName = data.eventName
            // 判断是否欠费
              let oFrame = document.getElementById('frame_tab_M_CALL_WORKBENCH');
              const {code} = await CallCenterApi.agentGetCost()
              let isOverCost = code !== 0

              switch (data.PhoSta) {
              case 0: //通话完成
                this.showCallCenter = false
                this.isTalking = false
                this.handleClearTimer();
                if(!isOverCost) {
                  this.callData.callState = data.eventName
                  if (this.isJumpCallCenterWorkbench) {
                    this.openCallCenterWorkbench()
                  }
                }
                oFrame?.contentWindow?.postMessage({type:'telIsOver'},'*')
                sessionStorage.removeItem('callCenterSourceData')
                break;
              case 4: // 外呼中
                break;
              case 5: // 来电振铃
              // 获取呼出&呼入的联系人信息 是否是已建立的客户
                const callType = data.CallType  // callType ：1呼出  2呼入 4呼入转
                let phone = ""
                if(callType == 1){
                  phone = data.Called
                }else if(callType == 2){
                  phone = data.Caller
                } else if(callType == 7){
                  // 咨询转接来电 Others：客户号码 Caller：发起咨询的坐席号
                  phone = data.Others
                }
                this.getLinkMenInfo(recordId, phone, data)
                if(!isOverCost) { // 如果欠费，呼入直接拒接，呼出则提示话费不足
                  this.showCallCenter = true
                  if(this.isMicroSip && callType==1){
                    // 软电话外呼提示用户
                    this.$platform.notification({
                        title: this.$t('common.base.toast'),
                        message: this.$t('system.callCenter.useSoftPhoneTransfer'),
                        type: 'warning',
                    })
                  }
                } else {
                // 呼入拒接，呼出提示话费不足的逻辑在ctisdk中做了
                  if(callType === 2) {
                    ctiRefuse()
                  }
                }
                break;
              case 6: // 接通
                this.callData.ringTime = data.Time
                this.callData.callState = data.eventName
                this.isTalking = true;
                this.handleRunTimer();

                if (data.CallType === 2 && !this.isJumpCallCenterWorkbench) return;
                // this.showCallCenter = false;
                if (this.isJumpCallCenterWorkbench) {
                  this.openCallCenterWorkbench();
                }
                this.zoomOut();
                break;
              case 21: // 咨询中
                oFrame?.contentWindow?.postMessage({type:'setConsultStatus',val:2},'*');
                this.$message(this.$t('system.callCenter.consultPending'))
                break;
              case 22: // 咨询成功
                oFrame?.contentWindow?.postMessage({type:'setConsultStatus',val:3},'*');
                this.$message.success(this.$t('system.callCenter.consultSuccess'))
                break;
              case 24: // 咨询未呼通
                oFrame?.contentWindow?.postMessage({type:'setConsultStatus',val:1},'*');
                this.$message.error(this.$t('system.callCenter.consultFailed'))
              case 35: // 电话转接
                oFrame?.contentWindow?.postMessage({type:'setIsConsul',val:true},'*');
                this.$message.success(this.$t('system.callCenter.phoneTransfer'))
                break;
              default:
                break;
              }
            }
          });
        });
        
      }catch(err){
        err && this.$message.error(err)
      }
    },
    // 更新呼叫中心sdk token
    async updateCtiSdkToken() {
      try{
        await this.getAgentGetToken()
        const { token } = this.frameForCallCenterData
        window.CTI.config.setState({ token })
      }catch(err){
        this.$message.error(err)
      }
    },

    /**
     * @description: 获取联系人信息
     * @param {Number} recordId 通话记录id
     * @param {String} phone 呼入/呼出 电话号码
     * @param {Object} data SDK ws 回调数据
     */
    getLinkMenInfo(recordId, phone, data) {
      CallCenterApi.agentGetLinkmanInfo({phone})
        .then(res => {
          if(res.code === 0) {
            const {CallType, eventName, Time, CallerAreaName} = data
            this.callData = Object.assign(res.result, {
              id: recordId,
              callType: CallType,
              ringTime: Time,
              callState: eventName,
              CallerAreaName,
              transferSeatCaller: CallType == 7 ? data?.Caller : '', // 发起咨询的坐席号吗
            })
          }
        })
        .catch(err => {console.error(err)})
    },

    /**
     * @description: 来电弹窗跳转
     * @param {Number} type 1/2/3/4 今日来电/今日去电/客户事件/客户工单
     */
    callPopupHandleJump(type) {
      const phone = this.callData.phone
      if(type === 1 || type === 2) {
        openAccurateTab({
          type: PageRoutesTypeEnum.PageCallCenterStage,
          params: `keyword=${phone}`,
          reload: true,
        });
      } else if(type === 3) {
        openAccurateTab({
          type: PageRoutesTypeEnum.PageEventList,
          params: `keyword=${phone}`,
          reload: true,
        });
      } else if(type === 4) {
        openAccurateTab({
          type: PageRoutesTypeEnum.PageTaskList,
          params: `keyword=${phone}`,
          reload: true,
        });
      }
      const trackId = ([
        '',
        'TODAY_CUSTOMER_CALLS_RECEIVED',
        'TODAY_OUTGOING_CUSTOMER_CALLS',
        'VIEW_CUSTOMER_EVENTS',
        'VIEW_CUSTOMER_WORK_ORDER'
      ])[type]
      this.$track.clickStat(this.$track.formatParams(trackId, this.callData.callType == 1 ? 'OUTBOUND_CALL' : 'INCOMING_CALL'));
    },
    async getAccountInfo () {
      try {
        const { code, result } = await CallCenterApi.getAccountInfo();
        // result为null未申请开通
        if (code !== 0 || !result) {
          return;
        }
        // 审核状态：0待审核，1已审核
        if (result.verifyStatus == 1) {
          this.has_call_center_module = true;
          if ('WebSocket' in window) {
            if(!CTI){
              this.initCtiSdk();
            }
          } else {
            alert('current browser Not support websocket');
          }

          return true;
        }
      } catch (error) {
        console.error(error);
      }
    },
    openCallCenterWorkbench () {
      let params = ''
      if(this.callData && this.callData.id) {
        let { id, todayCallInNum, name, phone, callType, callState, ringTime } = this.callData
        name = name ? name : ''
        params = `id=${id}&dialCount=${todayCallInNum}&linkmanName=${name}
        &callPhone=${phone}&callType=${callType}&callState=${callState}&ringTime=${ringTime}`
      }
      openAccurateTab({
        type: PageRoutesTypeEnum.PageSecurityCallcenterWorkbench,
        params,
        reload: true
      })
    },
    goCallCenterWorkbench () {
      openAccurateTab({
        type: PageRoutesTypeEnum.PageSecurityCallcenterWorkbench,
        reload: true
      })
    },
    // 更新坐席状态
    async changeCallCenterState(data){
      try{
        await this.updateSeatStatus(data)
        // status 1：签入 0：签出
        if(data.status){
          // 前端调用sdk签入 登录前
          await this.getAgentGetToken()
          if(CTI){
            CTI.Agent.login({
              bindTel:this.frameForCallCenterData.agentPhone,
              loginType:1,
            })
          }else{
            this.getAccountInfo()
          }
        }else{
          console.log('强制签出')
        }
      }catch(err){
        console.log(err)
      }
      
    },
    // 后端更新坐席状态
    updateSeatStatus(data) {
      return new Promise((resolve)=>{
        CallCenterApi.agentStatusUpdate({
          agentId:this.frameForCallCenterData.id,
          agentStatus: data.status
        }).then(res=>{
          if (res.code !== 0) return this.$platform.notification({
            title: this.$t('common.base.tip.operationFail'),
            message: res.message || '',
            type: 'error',
          });
          this.frameForCallCenterData.status = data.status;
          this.frameForCallCenterData.statusDescription = data.statusDescription;
          resolve()
        })
      })
    },
    // 查询坐席的转接手机号
    async queryTransferPhone(){
      const params = {
        agentId:this.frameForCallCenterData.id
      }
      const {code, result, message} = await CallCenterApi.queryTransferPhone(params)
      if(code == 0){
        this.callTransferPhone = result.phone
      }else{
        this.$message.warning(message)
      }
    },
    // 设置坐席的转接手机号
    async updateTransferPhone(){

      if(!this.callTransferPhone){
        this.$message.error(this.$t('common.base.tip.pleaseInputValidPhoneNumber'))
        return
      }
      const params = {
        agentId:this.frameForCallCenterData.id,
        phone:this.callTransferPhone
      }
      try{
        const {code, message} = await CallCenterApi.updateTransferPhone(params)
        if(code == 0){
          this.$message.success(this.$t('common.base.tip.settingSuccess'))
          this.callTransferPhoneVisible = false
          // if(this.frameForCallCenterData.status == 0){
          //   this.forceLogout()
          // }
          this.dialogVisible = false;
        }else{
          this.$message.warning(message)
        }
      }finally{
        this.queryTransferPhone()
      }
    },
    // 后端强制迁出
    forceLogout(){
      let data = this.frameForCallCenterData.statusList.find((item)=>item.status == 0)
      this.updateSeatStatus(data)
    },
    // 查询用户信息
    async getAgentGetToken(){
      try{
        const getTokenRes = await CallCenterApi.agentGetToken()
        if(getTokenRes.code === 0) {
          const { token, agentPhone, agNo, agentMessage, offLineAmswerState } = getTokenRes.result
          this.openOffLine = offLineAmswerState
          this.frameForCallCenterData = Object.assign(agentMessage, {agNo, agentPhone, token}) // 用于展示frame层 坐席信息
          localStorage.setItem('call_center_agent', 1) //绑定了中通天鸿坐席
          // 查询外呼号码
          this.queryTransferPhone()
        } else if(getTokenRes.code === 1){
          this.frameForCallCenterData = null
          let message = getTokenRes.message
          if(message==='您未被绑定坐席，请联系管理员绑定'){
            console.log('未绑定坐席-呼叫中心')
            return Promise.reject(false)
          }else{
            return Promise.reject(getTokenRes.message || this.$t('common.base.requestError'))
          }
        }else{
          this.frameForCallCenterData = null
          return Promise.reject(getTokenRes.message || this.$t('common.base.requestError'))
        }
      }catch(err){
        console.log(err)
        return Promise.reject(this.$t('common.base.requestError'))
      }
    },
    // 绑定坐席和解绑的回调
    async bindingCallBack(payload){
      console.log(payload)
      try{
        if(payload.content.seatOperate == 'bind'){
        // 绑定
          this.$alert(this.$t('system.callCenter.bindSuccess'), this.$t('common.base.toast'), {
            confirmButtonText: this.$t('common.button.iKnow'),
          });
        }else if(payload.content.seatOperate == 'unbind'){
          this.$alert(this.$t('system.callCenter.unBindSuccess'), this.$t('common.base.toast'), {
            confirmButtonText: this.$t('common.button.iKnow'),
          });
          this.frameForCallCenterData = null
        }
      }catch(err){
        this.$message.error(err)
      }
    },
    controlCallCenter () {
      return {
        set: (e) => {
          this.isTalking = e;
        },
        get: () => {
          return new Promise((resolve, reject) => {
            let res_ = this.isTalking;
            resolve(res_)
          })
        },
        clear: () => {
          this.isTalking = false;
        },
        getAgNo:()=>{
          return this.frameForCallCenterData.agNo
        },
      }
    },
    async queryAgentUserType(id){
      const {code,result} = await CallCenterApi.queryAgentUserType({agentId:id})
      if(code==0){
        this.isMicroSip =  result?.useType == 2
      }
    },
    setSeatStatus(data){
      if(data.MT == 3 || data.MT == 4 ){
       this.seatStatus = data.status || ''
      }
      if(data.MT == 6 ){
       this.seatStatus = data.realStatus || data.status || ''
      }
      if(data.MT==10){
        this.seatStatus = data.status||'坐席异常'
      }
    },
    offlineTransfer() {
      this.dialogVisible = true
      this.$track.clickStat(this.$track.formatParams('SET_OFFLINE_TRANSFER'))
    },
    makePhoneCall(tel){
      this.$track.clickStat(this.$track.formatParams('DIAL_OUT'));
      if(!tel) return
      this.showCallCenter = true;

      try {
        ctiCallOut(tel)
      } catch (error) {
        console.error(error);
      }
    },
    answerPhone(isMicroSip) {
      this.ctiSipAnswer(isMicroSip)
      this.$track.clickStat(this.$track.formatParams('ANSWER_PHONE'))
    },
    refusePhone() {
      this.ctiRefuse()
      this.$track.clickStat(this.$track.formatParams('REJECT_CALL'))
    },
    callOutCancel() {
      this.ctiCallOutCancel()
      this.$track.clickStat(this.$track.formatParams('CANCEL_OUTGOING_CALL', this.isOnlyShowCallOut ? 'INCOMING_CALL' : 'OUTBOUND_CALL'))
    },
    async openChange(value) {
      try {
        const params = {
          offLine:value == 1,
          agentId: this.frameForCallCenterData.id
        }
        const { code, message } = await CallCenterApi.offLineAnswer(params)
        if (code != 0) {
          this.$message.error(message)
          this.openOffLine = (value == 1 ? 0 : 1)
        }
      } catch (error) {
        console.log(error)
      }
    },
    // 添加来源参数
    addSourceData(data) {
      try {
        const sourceData = JSON.parse(sessionStorage.getItem('callCenterSourceData')) || {}
        return {...data,...sourceData}
      } catch (error) {
        console.log(error)
        return data
      }
    }
  },
};
</script>
<style scoped lang="scss">
  .frame-quick-phoneServiceStatus{
    font-size: 14px;
    padding: 0 12px;
    
    .status-text{
      color: #8C8C8C;
    }
    .icon-dianhua1{
      color: #8C8C8C;
      cursor: pointer;
    }
    .status-dot {
      margin-right: 6px;
    }

  }
  .in-call {
    background: #67C23A;
    border-radius: 20px 20px 20px 20px;

    span {
      color: #FFFFFF;
    }
  }
  .other-call {
    background: $color-primary-light-6;
    border-radius: 20px 20px 20px 20px;

    span {
      color: #FFFFFF;
    }
  }
  .call-center-box{
  position: fixed;
  width: 400px;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  transform-origin: center top;
  z-index: 2001;
  background: #fff;
  border: 1px solid #ebeef5;   

  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  .customer-name{
    color: $text-color-main;
    font-size: 24px;
    margin: 14px 0;
    color: #333;
  }
  p > span {
    color: #ed3f14;
  }

  .divider{
    height: 1px;
    width: 100%;
    background: #f5f5f5;
  }

  .call-ripple{
    position:relative;
    width: 90px;
    height: 90px;
    .icon-ripple {
      position: absolute; 
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      img {
        width: 48px;
        height: 48px;
        border-radius: 50%;
      }
      div[class^="ripple"] {
          position: absolute;
          top: 50%;
          left: 50%;
          transform: translate(-50%, -50%);
          width: 48px;
          height: 48px;
          box-shadow: 0 0 1.5px $color-primary;
          border-radius: 50%;
          animation: ripple 1.2s linear infinite;
      }
      div.ripple2 {
          animation-delay: 0.4s;
      }
     
    }
  }

  .call-in,.call-out{
    width: 100%;
    display: flex;
    // flex-direction: column;
    justify-content: space-between;
    flex-wrap: wrap;
    padding: 0 10px;
    a {
      width: 50%;
      text-decoration: underline;
      color: $color-primary-light-6;
      padding: 0 10px;
      cursor: pointer;
      margin-bottom: 10px;
      font-size: 16px;
      &:nth-child(odd) {
        text-align: right;
      }
      &:nth-child(even) {
        text-align: left;
      }
    }
  }

  .call-opt-btn {
    margin: 10px 0 20px 0;
  }

  .last{
    width: 100%;
    background:#FB602C;
    height: 26px;
    padding: 4px 0;
    margin-bottom: 0;
    color: #fff;
    opacity: 0.8;
    text-align: center;
  }

  @keyframes ripple {
    0% {}
    50% {
        width: 70px;
        height: 70px;
        opacity: 1;
    }
    100% {
        width: 90px;
        height: 90px;
        opacity: 0;
    }
  }

}

.call-center-dialog {
  position: fixed;
  width: 400px;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  transform-origin: center top;
  z-index: 2001;
  background: #fff;
  border: 1px solid #ebeef5;  
  box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);

  .dialog-header {
    height: 46px;
    line-height: 46px;
    padding: 0 24px;
    text-align: right;

    i {
      font-size: 16px;
      color: #595959;
      cursor: pointer;
    }
  }

  .dialog-main {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 24px 24px 32px;
    color: #595959;
    font-size: 14px;

    &-phone {
      font-size: 32px;
      color: #3D3D3D;
      &-forwarding-text {
        font-size: 26px;
      }
    }

    &-transferSeat {
      font-size: 18px;
      margin-top: 6px;
    }

    &-address {
      margin-top: 8px;
    }

    &-customer {
      width: 100%;
      display: flex;
      flex-wrap: wrap;
      justify-content: center;

      &-item {
        max-width: 150px;
        text-overflow: ellipsis;
        overflow: hidden;
        white-space: nowrap;
        background: #ECF5FF;
        border-radius: 4px 4px 4px 4px;
        padding: 4px 12px;
        margin-top: 12px;
        color: $color-primary-light-6;
        cursor: pointer;
      }
    }
    &-tags {
      margin: 10px 0;
    }

    .dialog-main-customer-item + .dialog-main-customer-item {
      margin-left: 8px;
    }

    &-name {
      font-size: 18px;
      margin-top: 8px;
    }

    &-time {
      font-size: 16px;
      height: 50px;
      line-height: 50px;
      margin: 16px 0 24px;
    }

    &-btn {
      width: 176px;
      height: 82px;
      display: flex;
      justify-content: space-between;

      &-item {
        height: 100%;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: space-between;

        div {
          width: 48px;
          height: 48px;
          line-height: 48px;
          text-align: center;
          border-radius: 100%;
          background: $color-primary-light-6;
          cursor: pointer;

          i {
            font-size: 24px;
            color: #fff;
          }
        }

        .reject {
          background: #EE0A24;
          transform: rotate(124deg);
        }

        .accept {
          background: #67C23A;
        }

        .jump i {
          font-size: 18px;
        }

        span {
          color: #262626;
        }
      }
    }

    &-statistics {
      width: 250px;
      margin: 24px 0;
      
      div {
        display: flex;
        justify-content: space-between;

        span {
          cursor: pointer;
          color: $color-primary-light-6;
          border-bottom: 1px solid $color-primary-light-6;
        }
      }

      div:last-child {
        margin-top: 8px;
      }
    }
  }
}

.desc{
  margin-bottom: 10px;
}
.setting-href {
  color: $color-primary;
  font-size: 14px;
  display: inline-block;
  width: 70px;
  text-align: right;
  cursor: pointer;
}
::v-deep .el-dropdown-item:hover {
  background: $hover-bg-color-level-1 !important;
  color: $text-color-regular !important;
}
::v-deep .el-dropdown-menu__item {
  font-size: 14px;
}
::v-deep .el-dialog__headerbtn {
  top: 2px;
}
::v-deep .el-dialog__body {
  padding: 60px 50px;
}
</style>
<style lang="scss">
  .custom-popper{
    z-index: 99 !important;
  }
  .call-transfer{
    .icon-shezhi{
      color: rgb(140, 140, 140) !important;
      font-size: 14px;
    }
  }
  .call-transfer-main{
    color: rgb(140, 140, 140);
    .el-input-group__append{
      border: 1px solid #e0e1e2 !important;
      border-radius: 0 !important;
      padding: 0;
      .subBtn{
        width: 100%;
        text-align: center;
        padding: 0 15px;
        cursor: pointer;
      }
    }
  }
</style>
